package com.ruoyi.framework.aspectj;

import com.ruoyi.common.annotation.StockLog;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.product.domain.StockLogs;
import com.ruoyi.product.service.IStockLogsService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class StockLogAspect {
    @Autowired
    private IStockLogsService stockLogsService;

    // 定义切入点，标记了 @InventoryLog 的方法会被切入
    @Pointcut("@annotation(stockLog)")
    public void logPointCut(StockLog stockLog){}

    @AfterReturning(value = "logPointCut(stockLog)", argNames = "joinPoint,stockLog")
    public void saveStockLog(ProceedingJoinPoint joinPoint,StockLog stockLog){
        // 获取方法的参数
        Object[] args = joinPoint.getArgs();

        Long productId = (Long) args[0];//商品ID

        Long quantityChange = (Long) args[1];//变更数量

        Long currentStock = stockLogsService.getProductStock(productId);

        StockLogs stockLogs = new StockLogs();
        stockLogs.setProductId(productId);
        stockLogs.setQuantityChange(quantityChange);
        stockLogs.setQuantitySum(currentStock);
        stockLogs.setReason(stockLog.reason().getDescription());
        stockLogs.setCreatedTime(DateUtils.getNowDate());
        stockLogs.setUpdatedTime(DateUtils.getNowDate());

        stockLogsService.insertStockLogs(stockLogs);
    }

}
